package com.jdcjk.project.main.view.baidu;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.jdcjk.Constant;
import com.jdcjk.R;
import com.jdcjk.UrlAddress;
import com.jdcjk.base.presenter.BasePresenter;
import com.jdcjk.base.view.BaseFragment;
import com.jdcjk.chat.enity.MessageBean;
import com.jdcjk.project.car.view.CarActivity;
import com.jdcjk.project.car.view.TerminalDetailsActivity;
import com.jdcjk.project.main.model.entity.CarListInfo;
import com.jdcjk.project.main.model.entity.TerminalInfoListResult;
import com.jdcjk.project.main.presenter.MainPresenter;
import com.jdcjk.util.BaiDuMapUtil;
import com.jdcjk.util.PreferencesUtils;
import com.jdcjk.view.LoadingDialog;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;

import static com.jdcjk.Constant.UserInfo.account;

/**
 * Created by Administrator on 2017/2/13 0013.
 */

public class BDCarMonitorFragment extends BaseFragment<MainPresenter> {
    private final String TAG = BDCarMonitorFragment.class.getSimpleName();
    private TextureMapView mMapView;
    private BaiduMap mBaiduMap;
    private ImageView mapType_imageView;
    private boolean isTouch = false;
    private SparseArray<Marker> carMarkerArray;
    private SparseArray<LatLng> carLatLngArray;
    private int currentIndex = 1000;
    //车辆信息List
    private List<CarListInfo> carInfoList = new ArrayList<>();
    //车辆位置刷新button
    ImageButton carInfoRefresh_button;
    //加载dialog
    private LoadingDialog loadingDialog;
    //地图放大等级
    private float zoomLevel = 20;

    //车辆信息窗口显示等级（0为不显示，1为小窗口，只显示名字，2位大窗口，显示车辆状态，acc等信息）
    private int carWindowsLevel = 1;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_baidu_car_monitor;
    }

    @Override
    public MainPresenter bindPresenter() {
        presenter = new MainPresenter(getContext());
        return presenter;
    }

    @Override
    public void initContentView(View viewContent) {
        mMapView = (TextureMapView) viewContent.findViewById(R.id.fragment_car_monitor_mapview);
        //开启硬件加速
        mMapView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        mapType_imageView = (ImageView) viewContent.findViewById(R.id.fragment_car_monitor_map_type);
        mapType_imageView.setOnClickListener(this);
        viewContent.findViewById(R.id.fragment_car_monitor_previous).setOnClickListener(this);
        viewContent.findViewById(R.id.fragment_car_monitor_next).setOnClickListener(this);
        carInfoRefresh_button = (ImageButton) viewContent.findViewById(R.id.car_info_refresh_btn);
        carInfoRefresh_button.setOnClickListener(this);
    }

    public void setCarList(List<CarListInfo> carInfoList) {
        this.carInfoList = carInfoList;
        //坐标转换
        for (int i = 0; i < carInfoList.size(); i++) {
            LatLng latLng = new LatLng(carInfoList.get(i).getLatitude(), carInfoList.get(i).getLongitude());
            latLng = BaiDuMapUtil.baiduLatLngEncrypt(latLng);
            carInfoList.get(i).setLatLng(latLng.latitude, latLng.longitude);
        }
    }


    @Override
    public void initData() {
        super.initData();
        //必须在onCreateView之后执行，否则为null
        mBaiduMap = mMapView.getMap();
        carMarkerArray = new SparseArray<>();
        carLatLngArray = new SparseArray<>();
        LatLng latLng;
        //判断车辆数是否为0
        if (carInfoList == null || carInfoList.size() == 0) {
            Toast.makeText(getActivity(), R.string.no_find_monitor_car, Toast.LENGTH_SHORT).show();
            return;
        }
        for (int i = 0; i < carInfoList.size(); i++) {
            latLng = new LatLng(carInfoList.get(i).getLatitude(), carInfoList.get(i).getLongitude());
            // 添加标注物
            Marker marker = addCarMarker(latLng, carInfoList.get(i));
            carMarkerArray.put(i, marker);
            carLatLngArray.put(i, latLng);
        }
        //移动到第一台车的位置
        latLng = new LatLng(carInfoList.get(0).getLatitude(), carInfoList.get(0).getLongitude());
        showInfoWindow(carMarkerArray.get(0));
        animateToLocation(latLng);
        // 设置初始值
        currentIndex *= carLatLngArray.size();
        //初始化加载dialog
        loadingDialog = new LoadingDialog(getActivity(), R.style.dialogTheme);
        //设置标志物点击监听
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                switch (carWindowsLevel) {
                    case 0:
                        carWindowsLevel = 1;
                        showInfoWindow(marker);
                        break;
                    case 1:
                        carWindowsLevel = 2;
                        showInfoWindow(marker);
                        break;
                    case 2:
                        mBaiduMap.hideInfoWindow();
                        carWindowsLevel = 0;
                        break;
                }

                return false;
            }
        });
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
                //手势操作地图，设置地图状态等操作导致地图状态开始改变。
            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
                //地图状态变化中
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                //地图状态改变结束
                zoomLevel = mapStatus.zoom;
            }
        });
    }

    /**
     * 在对应位置添加车辆标志物
     *
     * @param latLng      位置信息
     * @param carListInfo 车辆信息
     * @return
     */
    private Marker addCarMarker(LatLng latLng, CarListInfo carListInfo) {
        //摩托车图标（默认为在线图标）
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
                .fromResource(carListInfo.getDirection() > 180 ? R.mipmap.motorcycle_left_online : R.mipmap.motorcycle_right_online);//摩托车图标
        if (carListInfo.getOnline()) {
        } else {
            //连线图表
            bitmapDescriptor = BitmapDescriptorFactory
                    .fromResource(carListInfo.getDirection() > 180 ? R.mipmap.motorcycle_left_offline : R.mipmap.motorcycle_right_offline);//摩托车图标

        }
        // 创建标注物
        //构建MarkerOption，用于在地图上添加Marker,不可拖拽
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.icon(bitmapDescriptor);
        markerOption.draggable(false);
        //在地图上添加Marker，并显示
        final Marker marker = (Marker) (mBaiduMap.addOverlay(markerOption));
        return marker;
    }

    /**
     * 移动到坐标位置
     */
    public void animateToLocation(LatLng latLng) {
        //定义地图状态
        MapStatus mMapStatus = new MapStatus.Builder()
                //要移动的点
                .target(latLng)
                //放大地图到20倍
                .zoom(zoomLevel)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);
    }

    //当前车辆标志
    private int carPostion = 0;

    public void updataCarListInfo(String displayid, String carId, String cardNum) {
        carInfoList.get(carPostion).setDisplayid(displayid);
        carInfoList.get(carPostion).setCarId(carId);
        carInfoList.get(carPostion).setCardNum(cardNum);
        //刷新弹窗
        showInfoWindow(carMarkerArray.get(carPostion));
    }

    public void updataCarInfo(final MessageBean.TerminalStatusBean terminalStatusBean) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < carInfoList.size(); i++) {
                    //判断状态变化的车辆id
                    if (terminalStatusBean.getId() == carInfoList.get(i).getId()) {
                        //刷新车辆的数据，并刷新显示
                        carInfoList.get(i).setOnline(terminalStatusBean.isOnline());
                        carInfoList.get(i).setDisplayid(terminalStatusBean.getDisplayid());
                        carInfoList.get(i).setAcc(terminalStatusBean.isAcc());
                        carInfoList.get(i).setLatitude(terminalStatusBean.getLatitude());
                        carInfoList.get(i).setLongitude(terminalStatusBean.getLongitude());
                        Message msg = new Message();
                        //存储当前信息被修改的车辆在List中的位置
                        msg.arg1 = i;
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }
                }
            }
        }).start();
    }

    public void showInfoWindow(Marker marker) {
        //判断当前为第几个标志物
        for (int i = 0; i < carMarkerArray.size(); i = i + 1) {
            if (carMarkerArray.get(i).equals(marker)) {
                carPostion = i;
                break;
            }
        }
        //判断弹出窗口等级
        if (carWindowsLevel == 1) {
            View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_info_window_baidu_level_one, null);
            //设备名称textView
            TextView name_textView = (TextView) view.findViewById(R.id.dialog_info_window_car_displayid);
            //车牌号textview
            TextView carCardId_textview = (TextView) view.findViewById(R.id.dialog_info_window_car_card_id_tv);
            //车辆状态textview
            TextView carOnlineStatus_textview = (TextView) view.findViewById(R.id.dialog_info_window_online_status_tv);
            name_textView.setText(carInfoList.get(carPostion).getDisplayid());
            carCardId_textview.setText(carInfoList.get(carPostion).getCarId());
            carOnlineStatus_textview.setText(carInfoList.get(carPostion).getOnline() ? "在线" : "离线");
            //创建显示的弹窗布局，参数从左到右分别是：视图，显示位置，在y轴的偏移量
            InfoWindow infoWindow = new InfoWindow(view, marker.getPosition(), -65);
            mBaiduMap.showInfoWindow(infoWindow);
            //窗口点击监听，显示车辆详细信息窗口
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    carWindowsLevel = 2;
                    mBaiduMap.hideInfoWindow();
                    showInfoWindow(carMarkerArray.get(carPostion));
                }
            });
            return;
        }
        View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_info_window_baidu, null);
        //设备名称textView
        TextView name_textView = (TextView) view.findViewById(R.id.dialog_info_window_name_tv);
        //车辆状态textview
        TextView carStatus_textview = (TextView) view.findViewById(R.id.dialog_info_window_car_status);
        //车辆速度LinearLayout
        LinearLayout speed_lingearLayout = (LinearLayout) view.findViewById(R.id.dialog_info_window_speed_ll);
        //速度textView
        TextView speed_textView = (TextView) view.findViewById(R.id.dialog_info_window_speed_tv);
        //ACC状态textView
        TextView accStatus_textView = (TextView) view.findViewById(R.id.dialog_info_window_acc_status_tv);
        //通信时间textView
        TextView communicationTime_textView = (TextView) view.findViewById(R.id.dialog_info_window_communication_time_tv);
        //定位时间textView
        TextView loactionTime_textView = (TextView) view.findViewById(R.id.dialog_info_window_loaction_time_tv);
        //是否在线textView
        TextView onlineStatus_textView = (TextView) view.findViewById(R.id.dialog_info_window_online_status);
        //设备详情button
        ImageButton carTerminalSetBtn = (ImageButton) view.findViewById(R.id.terminal_set_btn);
        carTerminalSetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), TerminalDetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.TerminalInfo.terminalId, carInfoList.get(carPostion).getId());
                bundle.putString(Constant.FragmentInfo.fragment, Constant.FragmentInfo.mainActivity);
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
            }
        });
        name_textView.setText(carInfoList.get(carPostion).getDisplayid());
        //判断速度大小，若速度为0，则设置车辆状态为静止，不显示速度布局，否则显示为运动，显示车辆速度布局
        if (carInfoList.get(carPostion).getSpeed() == 0) {
            speed_lingearLayout.setVisibility(View.GONE);
            carStatus_textview.setText(R.string.motionless);
        } else {
            speed_lingearLayout.setVisibility(View.VISIBLE);
            String speed = carInfoList.get(carPostion).getSpeed() + getResources().getString(R.string.km_h);
            speed_textView.setText(speed);
            carStatus_textview.setText(R.string.movement);
        }
        communicationTime_textView.setText(carInfoList.get(carPostion).getUpdatedTime());
        loactionTime_textView.setText(carInfoList.get(carPostion).getLocationTime());
        accStatus_textView.setText(carInfoList.get(carPostion).getAcc() ? "开" : "关");
        onlineStatus_textView.setText(carInfoList.get(carPostion).getOnline() ? "在线" : "离线");
        onlineStatus_textView.setTextColor(getResources().getColor(carInfoList.get(carPostion).getOnline() ? R.color.green : R.color.orange));
        //窗口点击监听，显示车辆详细信息窗口
        InfoWindow infoWindow = new InfoWindow(view, marker.getPosition(), -65);
        mBaiduMap.showInfoWindow(infoWindow);
        //弹窗信息布局点击监听
        view.findViewById(R.id.dialog_info_window_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到单个设备界面
                Intent intent = new Intent(getActivity(), CarActivity.class);
                intent.putExtra(Constant.TerminalInfo.terminalId, carInfoList.get(carPostion).getId());
                startActivity(intent);
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                int i = msg.arg1;
                //刷新当前list
                LatLng latLng = new LatLng(carInfoList.get(i).getLatitude(), carInfoList.get(i).getLongitude());
                //坐标转换
                latLng = BaiDuMapUtil.baiduLatLngEncrypt(latLng);
                //移除同一车辆的标注
                carMarkerArray.get(i).remove();
                // 添加该车辆新的标注物
                Marker marker = addCarMarker(latLng, carInfoList.get(i));
                carMarkerArray.put(i, marker);
                carLatLngArray.put(i, latLng);
            }
        }
    };

    public void refreshCarInfo() {
        // 获取数据
        account = PreferencesUtils.getString(getActivity(), account);
        //获取用户设备列表
        presenter.getTerminalForUser(UrlAddress.GET_TERMINAL_FOR_USER, account, new BasePresenter.OnUIThreadListener<TerminalInfoListResult>() {
            @Override
            public void onBefore(Request request, int id) {
                loadingDialog.show();
                loadingDialog.setTextView(R.string.is_loaction);
            }

            @Override
            public void onAfter(int id) {
            }

            @Override
            public void onError(Call call, Exception e, int i) {
                loadingDialog.dismiss();
                Toast.makeText(getActivity(), R.string.system_exception, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(TerminalInfoListResult result) {
                switch (result.getStatus()) {
                    case "OK":
                        //终端列表信息
                        carInfoList = result.getResult();
                        LatLng latLng;
                        //判断车辆数是否为0
                        if (carInfoList == null || carInfoList.size() == 0) {
                            Toast.makeText(getActivity(), R.string.no_find_monitor_car, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        //清除之前的标志物
                        mBaiduMap.clear();
                        for (int i = 0; i < carInfoList.size(); i++) {
                            latLng = new LatLng(carInfoList.get(i).getLatitude(), carInfoList.get(i).getLongitude());
                            //坐标转换
                            latLng = BaiDuMapUtil.baiduLatLngEncrypt(latLng);
                            carInfoList.get(i).setLatLng(latLng.latitude, latLng.longitude);
                            // 添加标注物
                            Marker marker = addCarMarker(latLng, carInfoList.get(i));
                            carMarkerArray.put(i, marker);
                            carLatLngArray.put(i, latLng);
                        }
                        //移动到第一台车的位置
                        latLng = new LatLng(carInfoList.get(0).getLatitude(), carInfoList.get(0).getLongitude());
                        animateToLocation(latLng);
                        //显示弹窗
                        carWindowsLevel = 1;
                        showInfoWindow(carMarkerArray.get(0));
                        // 设置初始值
                        currentIndex *= carLatLngArray.size();
                        break;
                    case "FAILED":
                        break;
                }
                loadingDialog.dismiss();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    public BaiduMap getBDMap() {
        return mBaiduMap;
    }

    public ImageView getMapTypeImageView() {
        return mapType_imageView;
    }

    public SparseArray<Marker> getCarMarkerArray() {
        return carMarkerArray;
    }

    public SparseArray<LatLng> getCarLatLngArray() {
        return carLatLngArray;
    }

    public int getCurrentIndex() {
        return currentIndex;
    }

    public void setCurrentIndex(int currentIndex) {
        this.currentIndex = currentIndex;
    }

    public int getCarWindowsLevel() {
        return carWindowsLevel;
    }

    public void setCarWindowsLevel(int carWindowsLevel) {
        this.carWindowsLevel = carWindowsLevel;
    }

    /**
     * 关闭当前所有设备
     */
    public void closeAllTerminal() {
        for (int i = 0; i < carInfoList.size(); i++) {
            //刷新车辆的数据，并刷新显示
            carInfoList.get(i).setOnline(false);
            carInfoList.get(i).setAcc(false);
            Message msg = new Message();
            msg.what = 1;
            handler.sendMessage(msg);
        }
    }

}
